package com.exercise.widgets.chip.wrapper

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import com.google.android.material.chip.Chip

abstract class BaseDynamicChipAdapter<T>(
    @LayoutRes val layoutResId: Int,
    data: MutableList<T>? = null
) : DynamicChipView.Adapter<T>() {
    var data = data ?: arrayListOf()
        internal set
    var chipViewOrNull: DynamicChipView? = null
        private set
    val chipView: DynamicChipView
        get() {
            checkNotNull(chipViewOrNull) {
                "Please get it after onAttachedToChipView()"
            }
            return chipViewOrNull!!
        }
    protected val context: Context
        get() = chipView.context

    /**
     * 已选择item下标列表
     */
    protected val checkedIndexList: MutableList<Int> = mutableListOf()

    /**
     * 已选的Item下表
     * 单选情况下可以直接通过该变量获取已选item
     */
    protected val checkedIndex: Int?
        get() {
            if (checkedIndexList.isEmpty()) {
                return null
            }
            return checkedIndexList[0]
        }

    fun setList(list: Collection<T>?) {
        if (this.data !== list) {
            this.data.clear()
            if (!list.isNullOrEmpty()) {
                this.data.addAll(list)
            }
        } else {
            if (!list.isEmpty()) {
                val newList = ArrayList(list)
                this.data.clear()
                this.data.addAll(newList)
            } else {
                this.data.clear()
            }
        }
        notifyDateSetChanged()
    }

    /**
     * 重置已选数据
     *
     * @param index 可变参数，传入要选择的item下标
     */
    fun resetCheckedIndex(vararg index: Int) {
        checkedIndexList.clear()
        checkedIndexList.addAll(index.toList())
        notifyDateSetChanged()
    }

    override fun onCreateItemChipView(index: Int, parent: ViewGroup): Chip {
        val chip = LayoutInflater.from(context).inflate(
            layoutResId,
            parent,
            false
        ) as Chip
        chip.isChecked = checkedIndexList.contains(index)
        return chip
    }

    override fun onBindItem(index: Int): String {
        return bindItem(data[index])
    }

    abstract fun bindItem(item: T): String

    override fun updateCheckedItems(checkedIndexs: List<Int>) {
        checkedIndexList.clear()
        checkedIndexList.addAll(checkedIndexs)
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onAttachedToChipView(chipView: DynamicChipView) {
        chipViewOrNull = chipView
    }

    override fun onDetachedFromChipView(chipView: DynamicChipView) {
        chipViewOrNull = null
    }
}